package com.colter.project.sample.thread.part04.test1;

import java.util.concurrent.Executors;
import java.util.concurrent.RejectedExecutionHandler;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

public class Test9 {
	public static void main(String[] args) {
		RejectTaskController rejectTaskController = new RejectTaskController();
		ThreadPoolExecutor executor = (ThreadPoolExecutor) Executors.newCachedThreadPool();
		executor.setRejectedExecutionHandler(rejectTaskController);

		System.out.println("Main: start");
		for (int i = 0; i < 5; i++) {
			Task9 task = new Task9("Task" + i);
			executor.submit(task);
		}

		System.out.println("Main: shutting down executor.");
		executor.shutdown();
		Task9 task = new Task9("Reject Task");
		executor.submit(task);
		System.out.println("Main: end.");

	}
}

class RejectTaskController implements RejectedExecutionHandler {

	@Override
	public void rejectedExecution(Runnable r, ThreadPoolExecutor executor) {
		System.out.println("RC: The task has been rejected. " + r.toString());
		System.out.println("RC: " + executor.toString());
		System.out.println("RC: Terminated. " + executor.isTerminated());
		System.out.println("RC: Terminating. " + executor.isTerminating());
	}
}

class Task9 implements Runnable {
	private String name;

	public Task9(String name) {
		super();
		this.name = name;
	}

	@Override
	public void run() {
		try {
			long duration = (long) (Math.random() * 10);
			System.out.println("Task waiting for " + duration);
			TimeUnit.SECONDS.sleep(duration);

		} catch (Exception e) {
			e.printStackTrace();
		}

		System.out.println("Task ending.");
	}

	@Override
	public String toString() {
		return this.name;
	}

}